<?php


/**
 * 登录
 */

namespace Api;

use Logic\CaptchaLogic;
use Logic\LoginLogic;
use Logic\RedisClientLogic;
use Logic\RegistLogic;

class LoginController extends CommonController
{

    /**
     * 登录
     */
    public function login()
    {
        $code = $_POST['code'];
        $type = $_POST['types'] ?? 'login';
        if (!in_array($type, ['login', 'regist'])) {
            $this->returnJson(-1, '访问类型错误!', []);
        }
        $random_code = trim($_POST['random_code']);
        $redis = RedisClientLogic::getInstance();
        $right_code = $redis->get($type . ':code:' . $random_code);
        if (strcasecmp($code, $right_code) !== 0) {
            $this->returnJson(-1, '验证码错误!', []);
        }
        $pwd = $_POST['pwd'];
        $user = trim($_POST['username']);
        if (mb_strlen($user) > 20) {
            return ['res' => -1, 'msg' => '用户名不能超过20位!'];
        }
        $res = LoginLogic::doLogin($pwd, $user);
        $this->returnJson($res['res'] ?? 0, $res['msg'] ?? '', $res['data'] ?? []);
    }

    /**
     * 注册
     */
    public function regist()
    {
        $random_code = trim($_POST['random_code']);
        $user = trim($_POST['username']);
        $pwd = $_POST['pwd'];
        $pwd2 = $_POST['pwd_confirm'];
        $nk_name = $_POST['nk_name'];
        $code = $_POST['code'];
        $type = $_POST['types'];
        $redis = RedisClientLogic::getInstance();
        $right_code = $redis->get($type . ':code:' . $random_code);
        if (strcasecmp($code, $right_code) !== 0) {
            $this->returnJson(-1, '验证码错误!', []);
        }
        if (!preg_match("/^[A-Za-z0-9.]{6,16}$/", $pwd)) {
            $this->returnJson(-1, '用户密码必须6-16字节并且必须包含数字、字母大小写!', []);
        }
        if ($pwd !== $pwd2) {
            $this->returnJson(-1, '两次密码输入不一致!', []);
        }
        if (mb_strlen($user) > 20) {
            $this->returnJson(-1, '用户名不能超过20位!', []);
        }
        if (mb_strlen($nk_name) > 20) {
            $this->returnJson(-1, '昵称不能超过20位!', []);
        }
        $res = RegistLogic::doRegist($user, $nk_name, $pwd);
        $this->returnJson($res['res'] ?? 0, $res['msg'] ?? '', $res['data'] ?? []);
    }

}